/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import path from 'path';

import { expect } from '@jest/globals';
import * as compressing from 'compressing';
import fse from 'fs-extra';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { commonJson5Operation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
};

const testCaseFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();

  const entryBuildProfilePath = path.resolve(projectRootPath, 'entry/build-profile.json5');
  await commonJson5Operation(entryBuildProfilePath, async (jsonContent) => {
    jsonContent.buildOption = {
      resOptions: {
        compression: {
          media: {
            enable: true,
          },
        },
      },
    };
  });

  // build hap
  const buildResult = await runHvigorAsync(
    projectRootPath,
    initExecuteCommand({
      mode: 'module',
      product: 'default',
      module: 'entry@default',
      tasks: 'assembleHap',
    }),
  );
  expect(buildResult.stdout).toContain('BUILD SUCCESSFUL');

  // 检查 resConfig.json 和 opt-compression.json
  const resConfigPath = path.resolve(projectRootPath, 'entry/build/default/intermediates/res/default/resConfig.json');
  const optCompressionPath = path.resolve(projectRootPath, 'entry/build/default/intermediates/res/default/opt-compression.json');
  const resConfigJson = fse.readJsonSync(resConfigPath);
  expect(resConfigJson.compression).toBe(optCompressionPath);
  const optCompressionJson = fse.readJsonSync(optCompressionPath);
  expect(optCompressionJson.context.extensionPath).toContain('libimage_transcoder_shared');
  expect(optCompressionJson.compression).toStrictEqual({
    media: {
      enable: true,
    },
    filters: [
      {
        method: {
          type: 'sut',
          blocks: '4x4',
        },
      },
    ],
  });

  // 解压 entry-default-unsigned.hap
  const unzipDir = path.resolve(projectRootPath, '.temp_unzip');
  const entryResultPath = path.resolve(projectRootPath, 'entry/build/default/outputs/default/entry-default-unsigned.hap');
  fse.ensureDirSync(unzipDir);
  await compressing.zip.uncompress(entryResultPath, unzipDir);

  // 检查解压后里面的图片是否被转码为 sut 格式
  const unzipMediaDir = path.resolve(unzipDir, 'resources/base/media');
  expect(fse.existsSync(path.resolve(unzipMediaDir, 'app_icon.sut'))).toBe(true);
  expect(fse.existsSync(path.resolve(unzipMediaDir, 'icon.sut'))).toBe(true);
  expect(fse.existsSync(path.resolve(unzipMediaDir, 'startIcon.sut'))).toBe(true);
};

TestCaseBuilder.builder()
  .caseName('resource_compression.test.ts')
  .description('纹理超压缩')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.AR).ohpmInstall(IsEnable.Enable).build())
  .testFun(testCaseFun)
  .load();
